package com.rzico.basics.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rzico.exception.CustomException;
import com.rzico.util.HttpUtils;
import com.rzico.util.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class Kuaidi100
{

    @Value("${kuaidi100.customer}")
    private String kuaidi100Customer;
    @Value("${kuaidi100.key}")
    private String kuaidi100Key;


    public List<String> getComInfo(String num) {
        List<String> com = new ArrayList<>();
        String ret = "";

            ret = HttpUtils.httpGet("http://www.kuaidi100.com/autonumber/auto?num="+num+"&key="+kuaidi100Key,null);

            JSONArray  arr = JSON.parseArray(ret);
            if (arr.size()==0) {
                throw new CustomException("无效快递单号");
            }

            for (int i=0;i<arr.size();i++) {
                JSONObject obj = arr.getJSONObject(0);
                com.add(obj.getString("comCode"));
            }

        return com;
    }

    /**
     * 查询快递信息
     * @param com 快递公司代码
     * @param nu 快递单号
     * @return
     */
    public Map<String, Object> getExpressInfo(String com ,String nu){
        Map<String, Object> data = new HashMap<String, Object>();
        try {
            Map<String,Object> pv = new HashMap<>();
            pv.put("com",com);
            pv.put("num",nu);
            pv.put("resultv2",1);
            String param = JSON.toJSONString(pv);
            String sign = MD5Utils.getMD5Str(param + kuaidi100Key + kuaidi100Customer).toUpperCase();

            ObjectMapper mapper = new ObjectMapper();
            URL url = new URL("https://poll.kuaidi100.com/poll/query.do?customer="+kuaidi100Customer+"&param=" + param+ "&sign=" + sign);
            data = mapper.readValue(url, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

}
